package dale.web.english.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import dale.web.english.model.English;
import dale.web.english.service.EnglishService;

@Controller
@RequestMapping("/english")
@SessionAttributes("english")
public class EnglishPostController {

	@Autowired
	private EnglishService service;
	
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public English create() {
		return new English();
	}
	
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public String create(@ModelAttribute @Validated English item, Errors errors, SessionStatus status, RedirectAttributes redirectAttributes) {
		if (errors.hasErrors())
			return "/english/create";
		
		service.create(item);
		
		status.setComplete();
		redirectAttributes.addFlashAttribute("msg", "Successfully processed.");
			
		return "redirect:/english/detail?no=" + item.getNo();
	}
	
	@RequestMapping(value = "/modify", method = RequestMethod.GET)
	public English modify(@RequestParam Integer no) {
		return service.detail(no);
	}
	
	@RequestMapping(value = "/modify", method = RequestMethod.POST)
	public String modify(@ModelAttribute @Validated English item, Errors errors, SessionStatus status, RedirectAttributes redirectAttributes) {
		if (errors.hasErrors())
			return "/english/modify";
		
		service.modify(item);
		
		status.setComplete();
		redirectAttributes.addFlashAttribute("msg", "Successfully processed.");
			
		return "redirect:/english/detail?no=" + item.getNo();
	}

}
